#-*- coding:utf-8 -*-

from socket import *
from time import ctime
import time
import sqlconnect
import zigbeemessage
'''
        short_and_ieee:3286-00124B001D1A980F%
        3286：代表网络短地址shortaddr
        00124B001D1A980F：代表IEEE地址
        %：代表结束符
        
        siyaosu:B65-4-95-89-90-0-233%
        B65：表示是由哪个终端上传上来的数据
        4-95：4/95表示报文重传率（越低越好）
        89-90：89/90表示报文接受率（越高越好）
        0：载波监听时间，0代表当前信道正常，1代表当前有人长时间占用信道
        233：衡量链路质量的一个指标值
        '''
print("=====================时间戳TCP服务器=====================");
def accesszigbee():
    HOST = ''  #主机号为空白表示可以使用任何可用的地址。
    PORT = 516  #端口号
    BUFSIZ = 2048  #接收数据缓冲大小
    ADDR = (HOST, PORT)

    tcpSerSock = socket(AF_INET, SOCK_STREAM) #创建TCP服务器套接字
    tcpSerSock.bind(ADDR)  #套接字与地址绑定
    tcpSerSock.listen(5) #监听连接，同时连接请求的最大数目
    print('等待客户端的连接...')
    while True:

        tcpCliSock, addr = tcpSerSock.accept()   #接收客户端连接请求
        print('取得连接:', addr)
        print ('-----------------------')
        #while True:
        data = tcpCliSock.recv(BUFSIZ)  #连续接收指定字节的数据，接收到的是字节数组
        #short_and_ieee:3286-00124B001D1A980F%
        #siyaosu:B65-0-74-60-60-0-247%
        try:

            '''
            if not data:  #如果数据空白，则表示客户端退出，所以退出接收
                print 'errrrrrrrrrror'
                continue
            '''
            if data.find('short_and_ieee') != -1: # 如果数据不是空白的
                print data, type(data)
                short_and_iee = data[data.find('short_and_ieee'):data.find('%')+1]
                print short_and_iee
                data1 = short_and_iee.split(":")
                #data[data.find('siyaosu'):]
                data2 = data1[1].split("-")
                interface = "zigbee"
                addr = data2[0]  # 短地址
                zigbeemessage.deletezigbeeinfo(addr)
                ip = data2[1][:-1]      # Ip
                create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                db = sqlconnect.connect()
                corsor = db.cursor()
                sql = "insert into zigbee_info(interface, addr, ip, create_time) values ('%s','%s','%s','%s')" %(interface, addr, ip, create_time)
                try:
                    corsor.execute(sql)
                    db.commit()
                    print 'insert zigbee success'
                except:
                    print 'error insert '
                    db.rollback()
                db.close()
            elif data.find('siyaosu') != -1:
                siyaosu = data[data.find('siyaosu'):data.find('%')+1]
                print '1111',siyaosu
                data1 = siyaosu.split(":")
                data2 = data1[1].split("-")
                interface = "zigbeeA"
                client = data2[0]             # 终端
               # print client
                zigbeemessage.deletezigbeeA(client)
                RetraRate = '{:.2f}%'.format(float(data2[1]) / float(data2[2])*100) # 重传率
                ReceRate = '{:.2f}%'.format(float(data2[3]) / float(data2[4])*100) # 接收率
                xindao = data2[5]             # 载波监听时间
                zhibiao = data2[6][:-1]            # 指标值
                #print ReceRate,RetraRate,xindao,zhibiao
                create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                db = sqlconnect.connect()
                corsor = db.cursor()
                sql = "insert into zigbeeA(interface, client, RetraRate, ReceRate, xindao, zhibiao, create_time) values ('%s','%s','%s','%s','%s','%s','%s')" %(interface, client, RetraRate, ReceRate, xindao, zhibiao,create_time)
                corsor.execute(sql)
                try:
                    corsor.execute(sql)
                    db.commit()
                    print 'insert zigbeeA success'
                except:
                    print 'errror insert zigbeeA'
                    db.rollback()
                db.close()
        except:
            continue
        tcpCliSock.send('[%s] %s' % (ctime(), data)) #向客户端发送时间戳数据

        tcpCliSock.close()  #关闭与客户端的连接
    tcpSerSock.close()
if __name__ == '__main__':
    accesszigbee()